package myFilter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyFilter implements Filter {
	public void destroy() {
	}
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		//为了便于方法的调用，进行数据类型转换
		HttpServletRequest request=(HttpServletRequest)req;
		HttpServletResponse response=(HttpServletResponse)res;
		/**
		 * 禁用浏览器缓存
		 */
		response.addHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control","no-cache,no-store,must-revalidate");
		response.addHeader("Cache-Control","pre-check=0, post-check=0");
		response.setDateHeader("Expires",0);
		/**
		 * 统一设置请求和响应的编码格式
		 */
		req.setCharacterEncoding("utf-8");
		//res.setCharacterEncoding("utf-8");
		//获取相对于上下文的请求路径
		String path=request.getServletPath();
		/**
		 * 对样式和图片放行
		 * 具体做法：以css和js结尾的放行
		 */
		if(path.endsWith(".css")||path.endsWith(".js")||path.endsWith(".jpg")){
			chain.doFilter(request, response);//放行
			return;
		}
		if("/login.jsp".equals(path)||"/DoLog.do".equals(path)){//登录页，登录路径放行
			chain.doFilter(request, response);//放行
			return;
		}
		if(request.getSession().getAttribute("Emp")==null){
			System.out.println("登录异常");
			/**
			 * 重定向：相对于服务器的根路径
			 * 1.获取相对于服务器的上下文路径：request.getContextPath()
			 * 2.获取相对于服务器的请求路径：request.getContextPath()+"/login.jsp"
			 */
			response.sendRedirect(request.getContextPath()+"/login.jsp");//不放行,重新定向到登录页
		}else {
			chain.doFilter(request, response);//放行
			return;
		}
	}
	public void init(FilterConfig arg0) throws ServletException {
	}
}
